<template>
  <div class="settimeout-diagnostic">
    <div class="diagnostic-header">
      <h1>🔍 setTimeout 性能诊断</h1>
      <p>专门解决 setTimeout 执行时间过长的问题</p>
    </div>

    <div class="diagnostic-content">
      <!-- 问题说明 -->
      <div class="problem-section">
        <h2>❓ 问题说明</h2>
        <div class="problem-card">
          <h3>🐌 慢函数检测: setTimeout 执行了 670ms</h3>
          <div class="problem-explanation">
            <p><strong>这意味着什么？</strong></p>
            <ul>
              <li>有一个 setTimeout 回调函数执行时间过长</li>
              <li>正常情况下的 setTimeout 回调应该很快执行完成（通常 &lt; 10ms）</li>
              <li>670ms 的执行时间明显异常，会影响页面性能</li>
            </ul>
            
            <p><strong>可能的原因：</strong></p>
            <ul>
              <li>🌐 <strong>浏览器扩展干扰</strong> - 翻译扩展、广告拦截器、语言检测扩展</li>
              <li>📜 <strong>外部脚本问题</strong> - 第三方脚本（分析工具、广告脚本）</li>
              <li>💻 <strong>代码逻辑问题</strong> - 回调函数中有复杂的计算或DOM操作</li>
              <li>🌍 <strong>网络请求超时</strong> - API调用阻塞或超时</li>
            </ul>
          </div>
        </div>
      </div>

      <!-- 实时监控 -->
      <div class="monitoring-section">
        <h2>📊 实时监控</h2>
        <div class="monitoring-controls">
          <el-button @click="startMonitoring" :disabled="isMonitoring" type="primary">
            开始监控
          </el-button>
          <el-button @click="stopMonitoring" :disabled="!isMonitoring" type="danger">
            停止监控
          </el-button>
          <el-button @click="clearRecords" type="warning">
            清除记录
          </el-button>
          <el-button @click="exportReport" type="success">
            导出报告
          </el-button>
        </div>

        <div class="monitoring-stats">
          <div class="stat-card">
            <div class="stat-icon">🐌</div>
            <div class="stat-content">
              <div class="stat-value">{{ slowTimeoutsCount }}</div>
              <div class="stat-label">慢函数数量</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">⏱️</div>
            <div class="stat-content">
              <div class="stat-value">{{ maxDuration }}ms</div>
              <div class="stat-label">最长执行时间</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">📈</div>
            <div class="stat-content">
              <div class="stat-value">{{ avgDuration }}ms</div>
              <div class="stat-label">平均执行时间</div>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🔄</div>
            <div class="stat-content">
              <div class="stat-value">{{ totalExecutions }}</div>
              <div class="stat-label">总执行次数</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 慢函数列表 -->
      <div class="slow-functions-section">
        <h2>🐌 慢函数列表</h2>
        <div v-if="slowTimeouts.length > 0" class="functions-list">
          <div v-for="timeout in slowTimeouts" :key="timeout.id" class="function-item">
            <div class="function-header">
              <div class="function-type">
                {{ timeout.isInterval ? 'setInterval' : 'setTimeout' }}
              </div>
              <div class="function-duration" :class="getDurationClass(timeout.duration)">
                {{ Math.round(timeout.duration) }}ms
              </div>
              <div class="function-count" v-if="timeout.count > 1">
                重复 {{ timeout.count }} 次
              </div>
            </div>
            <div class="function-details">
              <div class="function-delay">延迟: {{ timeout.delay }}ms</div>
              <div class="function-callback">
                <strong>回调函数:</strong>
                <code>{{ timeout.callback }}</code>
              </div>
              <div class="function-analysis">
                <strong>可能原因:</strong>
                <div class="analysis-tags">
                  <span v-if="isExternalScript(timeout.callback)" class="tag external">
                    🌐 外部脚本
                  </span>
                  <span v-if="isNetworkRequest(timeout.callback)" class="tag network">
                    🌍 网络请求
                  </span>
                  <span v-if="isDOMOperation(timeout.callback)" class="tag dom">
                    💻 DOM操作
                  </span>
                  <span v-if="isComputation(timeout.callback)" class="tag computation">
                    🧮 计算密集型
                  </span>
                  <span v-if="isThirdParty(timeout.callback)" class="tag third-party">
                    📦 第三方库
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="no-functions">
          <el-empty description="暂无慢函数记录" />
        </div>
      </div>

      <!-- 解决方案 -->
      <div class="solutions-section">
        <h2>💡 解决方案</h2>
        <div class="solutions-grid">
          <div class="solution-card">
            <div class="solution-icon">🌐</div>
            <div class="solution-content">
              <h3>禁用浏览器扩展</h3>
              <p>临时禁用翻译扩展、语言检测扩展等可能干扰的扩展</p>
              <el-button @click="openExtensionsPage" type="primary" size="small">
                打开扩展管理
              </el-button>
            </div>
          </div>
          
          <div class="solution-card">
            <div class="solution-icon">🕐</div>
            <div class="solution-content">
              <h3>使用无痕模式</h3>
              <p>在无痕模式下测试，排除扩展影响</p>
              <el-button @click="showIncognitoInstructions" type="primary" size="small">
                查看说明
              </el-button>
            </div>
          </div>
          
          <div class="solution-card">
            <div class="solution-icon">🧹</div>
            <div class="solution-content">
              <h3>清理浏览器缓存</h3>
              <p>清理浏览器缓存和Cookie，重置浏览器状态</p>
              <el-button @click="showClearCacheInstructions" type="primary" size="small">
                查看说明
              </el-button>
            </div>
          </div>
          
          <div class="solution-card">
            <div class="solution-icon">⚡</div>
            <div class="solution-content">
              <h3>代码优化</h3>
              <p>优化回调函数，减少计算量和DOM操作</p>
              <el-button @click="showCodeOptimizationTips" type="primary" size="small">
                查看技巧
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 实时日志 -->
      <div class="logs-section">
        <h2>📝 实时日志</h2>
        <div class="logs-container">
          <div v-for="log in logs" :key="log.id" class="log-item" :class="log.level">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
        <div class="logs-controls">
          <el-button @click="clearLogs" size="small">清除日志</el-button>
          <el-button @click="exportLogs" size="small" type="success">导出日志</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElButton, ElEmpty } from 'element-plus'

// 响应式数据
const isMonitoring = ref(false)
const slowTimeouts = ref([])
const logs = ref([])
const slowTimeoutsCount = ref(0)
const maxDuration = ref(0)
const avgDuration = ref(0)
const totalExecutions = ref(0)

// 监控间隔
let monitoringInterval = null

// 开始监控
const startMonitoring = () => {
  isMonitoring.value = true
  addLog('info', '开始监控 setTimeout 性能')
  
  monitoringInterval = setInterval(() => {
    updateStats()
  }, 1000)
}

// 停止监控
const stopMonitoring = () => {
  isMonitoring.value = false
  if (monitoringInterval) {
    clearInterval(monitoringInterval)
    monitoringInterval = null
  }
  addLog('info', '停止监控')
}

// 更新统计数据
const updateStats = () => {
  if (window.setTimeoutDiagnostic) {
    const report = window.setTimeoutDiagnostic.getSlowTimeoutsReport()
    slowTimeouts.value = report.slowTimeouts
    slowTimeoutsCount.value = report.totalSlowTimeouts
    
    if (report.slowTimeouts.length > 0) {
      maxDuration.value = Math.round(Math.max(...report.slowTimeouts.map(t => t.duration)))
      avgDuration.value = Math.round(report.summary.avgDuration)
      totalExecutions.value = report.slowTimeouts.reduce((sum, t) => sum + t.count, 0)
    }
  }
}

// 清除记录
const clearRecords = () => {
  if (window.setTimeoutDiagnostic) {
    window.setTimeoutDiagnostic.clearRecords()
    slowTimeouts.value = []
    slowTimeoutsCount.value = 0
    maxDuration.value = 0
    avgDuration.value = 0
    totalExecutions.value = 0
    addLog('info', '清除所有记录')
  }
}

// 导出报告
const exportReport = () => {
  if (window.setTimeoutDiagnostic) {
    window.setTimeoutDiagnostic.exportReport()
    addLog('success', '报告已导出')
  }
}

// 添加日志
const addLog = (level, message) => {
  logs.value.unshift({
    id: Date.now(),
    time: new Date().toLocaleTimeString(),
    level,
    message
  })
  
  if (logs.value.length > 100) {
    logs.value = logs.value.slice(0, 100)
  }
}

// 清除日志
const clearLogs = () => {
  logs.value = []
  addLog('info', '日志已清除')
}

// 导出日志
const exportLogs = () => {
  const logText = logs.value.map(log => 
    `[${log.time}] [${log.level.toUpperCase()}] ${log.message}`
  ).join('\n')
  
  const blob = new Blob([logText], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `settimeout-logs-${Date.now()}.txt`
  a.click()
  URL.revokeObjectURL(url)
  
  addLog('success', '日志已导出')
}

// 工具函数
const getDurationClass = (duration) => {
  if (duration > 1000) return 'critical'
  if (duration > 500) return 'warning'
  return 'normal'
}

const isExternalScript = (callback) => {
  const text = callback.toLowerCase()
  return text.includes('detect') || text.includes('translate') || text.includes('lang')
}

const isNetworkRequest = (callback) => {
  const text = callback.toLowerCase()
  return text.includes('fetch') || text.includes('xmlhttprequest') || text.includes('ajax')
}

const isDOMOperation = (callback) => {
  const text = callback.toLowerCase()
  return text.includes('queryselector') || text.includes('getelementbyid') || text.includes('innerhtml')
}

const isComputation = (callback) => {
  const text = callback.toLowerCase()
  return text.includes('for') || text.includes('while') || text.includes('math.')
}

const isThirdParty = (callback) => {
  const text = callback.toLowerCase()
  return text.includes('jquery') || text.includes('lodash') || text.includes('moment')
}

// 解决方案方法
const openExtensionsPage = () => {
  addLog('info', '尝试打开扩展管理页面')
  try {
    window.open('chrome://extensions/', '_blank')
    addLog('success', '已打开扩展管理页面')
  } catch (e) {
    addLog('error', '无法自动打开扩展管理页面，请手动访问')
  }
}

const showIncognitoInstructions = () => {
  addLog('info', '无痕模式说明:')
  addLog('info', 'Chrome: Ctrl+Shift+N')
  addLog('info', 'Firefox: Ctrl+Shift+P')
  addLog('info', 'Edge: Ctrl+Shift+N')
}

const showClearCacheInstructions = () => {
  addLog('info', '清理缓存说明:')
  addLog('info', 'Chrome: 设置 > 隐私和安全 > 清除浏览数据')
  addLog('info', 'Firefox: 设置 > 隐私与安全 > 清除数据')
  addLog('info', 'Edge: 设置 > 隐私、搜索和服务 > 清除浏览数据')
}

const showCodeOptimizationTips = () => {
  addLog('info', '代码优化技巧:')
  addLog('info', '1. 避免在 setTimeout 中进行大量计算')
  addLog('info', '2. 使用 requestAnimationFrame 替代 setTimeout 进行动画')
  addLog('info', '3. 缓存 DOM 查询结果')
  addLog('info', '4. 使用 Web Workers 处理计算密集型任务')
  addLog('info', '5. 避免同步的网络请求')
}

// 生命周期
onMounted(() => {
  addLog('info', 'setTimeout 诊断工具已加载')
  startMonitoring()
})

onUnmounted(() => {
  stopMonitoring()
})
</script>

<style scoped>
.settimeout-diagnostic {
  min-height: 100vh;
  background: #f8fafc;
  padding: 20px;
}

.diagnostic-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.diagnostic-header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  font-weight: 700;
}

.diagnostic-header p {
  font-size: 1.1rem;
  opacity: 0.9;
}

.diagnostic-content {
  max-width: 1200px;
  margin: 0 auto;
}

.problem-section,
.monitoring-section,
.slow-functions-section,
.solutions-section,
.logs-section {
  background: white;
  border-radius: 15px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.problem-section h2,
.monitoring-section h2,
.slow-functions-section h2,
.solutions-section h2,
.logs-section h2 {
  color: #1f2937;
  font-size: 1.5rem;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 3px solid #667eea;
}

.problem-card {
  background: #f9fafb;
  border-radius: 10px;
  padding: 25px;
  border-left: 5px solid #ef4444;
}

.problem-card h3 {
  color: #ef4444;
  font-size: 1.3rem;
  margin-bottom: 15px;
}

.problem-explanation ul {
  margin: 10px 0;
  padding-left: 20px;
}

.problem-explanation li {
  margin: 8px 0;
  line-height: 1.6;
}

.monitoring-controls {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
  flex-wrap: wrap;
}

.monitoring-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: #f8fafc;
  padding: 20px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  gap: 15px;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

.stat-card:hover {
  border-color: #667eea;
  transform: translateY(-2px);
}

.stat-icon {
  font-size: 2rem;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e0e7ff;
  border-radius: 50%;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 1.8rem;
  font-weight: 700;
  color: #1f2937;
}

.stat-label {
  font-size: 0.9rem;
  color: #6b7280;
}

.functions-list {
  max-height: 500px;
  overflow-y: auto;
}

.function-item {
  background: #f9fafb;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 15px;
  border-left: 5px solid #667eea;
}

.function-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.function-type {
  background: #667eea;
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
}

.function-duration {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
  font-weight: 600;
}

.function-duration.normal {
  background: #d1fae5;
  color: #065f46;
}

.function-duration.warning {
  background: #fef3c7;
  color: #92400e;
}

.function-duration.critical {
  background: #fee2e2;
  color: #991b1b;
}

.function-count {
  background: #e0e7ff;
  color: #667eea;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
}

.function-details {
  font-size: 0.9rem;
  color: #374151;
}

.function-delay {
  margin-bottom: 10px;
  font-weight: 500;
}

.function-callback {
  margin-bottom: 15px;
}

.function-callback code {
  background: #1f2937;
  color: #f9fafb;
  padding: 8px 12px;
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 0.8rem;
  display: block;
  margin-top: 5px;
  overflow-x: auto;
}

.analysis-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 8px;
}

.tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
}

.tag.external {
  background: #fef3c7;
  color: #92400e;
}

.tag.network {
  background: #dbeafe;
  color: #1e40af;
}

.tag.dom {
  background: #d1fae5;
  color: #065f46;
}

.tag.computation {
  background: #e0e7ff;
  color: #7c3aed;
}

.tag.third-party {
  background: #fce7f3;
  color: #be185d;
}

.solutions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.solution-card {
  background: #f8fafc;
  border-radius: 10px;
  padding: 20px;
  display: flex;
  gap: 15px;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

.solution-card:hover {
  border-color: #667eea;
  transform: translateY(-2px);
}

.solution-icon {
  font-size: 2rem;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e0e7ff;
  border-radius: 50%;
  flex-shrink: 0;
}

.solution-content {
  flex: 1;
}

.solution-content h3 {
  color: #1f2937;
  font-size: 1.1rem;
  margin-bottom: 8px;
}

.solution-content p {
  color: #6b7280;
  font-size: 0.9rem;
  margin-bottom: 15px;
  line-height: 1.5;
}

.logs-container {
  background: #1f2937;
  color: #f9fafb;
  padding: 20px;
  border-radius: 10px;
  max-height: 300px;
  overflow-y: auto;
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
  margin-bottom: 15px;
}

.log-item {
  margin: 3px 0;
  padding: 2px 0;
}

.log-time {
  color: #9ca3af;
  margin-right: 10px;
}

.log-item.info .log-message {
  color: #60a5fa;
}

.log-item.warning .log-message {
  color: #fbbf24;
}

.log-item.error .log-message {
  color: #f87171;
}

.log-item.success .log-message {
  color: #34d399;
}

.logs-controls {
  display: flex;
  gap: 10px;
}

.no-functions {
  text-align: center;
  padding: 40px;
}

@media (max-width: 768px) {
  .diagnostic-header h1 {
    font-size: 2rem;
  }
  
  .monitoring-controls {
    flex-direction: column;
  }
  
  .monitoring-stats {
    grid-template-columns: 1fr;
  }
  
  .solutions-grid {
    grid-template-columns: 1fr;
  }
  
  .function-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
